import time

import pytest
from selenium import webdriver

from business.Login.login_business import LoginBusiness
from common.readCofig import *
from common.read_yaml import ReadYaml
from business.commodity_list.commodity_list_bs import CommodityListBusiness
from business.add_commodity.add_commodity_bs import AddCommodityBusiness
data = ReadYaml("data.yml").get_yaml_data()#读取数据

Firefox = 'firefox'
Chrome = 'chrome'
IE = 'ie'
# Grid = 'grid'
ChromeHeadless = 'chrome-headless'
FirefoxHeadless = 'firefox-headless'


#session 是多个文件调用一次，可以跨.py文件调用，每个.py文件就是module
@pytest.fixture(scope="session")
def driver1(request):
    def end():
        print("全部用例执行完后 teardown quit dirver1")
        time.sleep(5)
        driver.quit()

    # 注册一个清理函数
    request.addfinalizer(end)
    global driver
    if browerType == Chrome:
        # chromeOptions 是一个配置 chrome 启动是属性的类。通过这个类，我们可以为chrome配置如下参数
        # 添加启动参数(add_argument)
        #设置 chrome 二进制文件位置 (binary_location)
        # 添加启动参数 (add_argument)
        # 添加扩展应用 (add_extension, add_encoded_extension)
        # 添加实验性质的设置参数 (add_experimental_option)
        # 设置调试器地址 (debugger_address)
        chrome_options = webdriver.ChromeOptions()
        driver = webdriver.Chrome(options=chrome_options)
        driver.maximize_window()
        # assert(1 == 3)
        login_zhangsan()
    elif browerType == ChromeHeadless:
        # chrome headless模式
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--window-size=1920x1080")
        chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
        chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
        chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片，提升运行速度

        driver = webdriver.Chrome(options=chrome_options)
        login_zhangsan()
    elif browerType == Firefox:
        # 本地firefox浏览器
        driver = webdriver.Firefox()
        driver.maximize_window()
        driver.implicitly_wait(timeout)
        login_zhangsan()

    elif browerType == FirefoxHeadless:
        # firefox headless模式
        firefox_options = webdriver.FirefoxOptions()
        firefox_options.headless = True
        driver = webdriver.Firefox(firefox_options=firefox_options)
        login_zhangsan()
    # elif browerType == Grid:
    #     # 通过远程节点运行
    #     chrome_capabilities = {
    #         "browserName": "chrome",
    #         "version": "",
    #         "platform": "ANY",
    #         "javascriptEnabled": True,
    #         # "marionette": True,
    #     }
    #
    #     driver = webdriver.Remote(hubIP, desired_capabilities=chrome_capabilities)
    #
    #     driver.set_window_size(1920, 1080)
    #
    # else:
    #     raise NameError("driver驱动类型定义错误！")

    return driver
    # yield driver
    # driver.close()

def login_zhangsan():
    driver.get(data['URL'] + '/#/login')
    driver.implicitly_wait(int(timeout))
    login1 = LoginBusiness(driver)
    time.sleep(15)
    print("data['login_zhangsan']['user_name']1111111111111",data['login_zhangsan']['user_name'])
    login1.login(data['login_zhangsan']['user_name'],data['login_zhangsan']['password'])

# @pytest.fixture
# def login_zhangsan():
#     _login(data['login_zhangsan']['user_name'], data['login_zhangsan']['password'])
#
# @pytest.fixture
# def login_lisi():
#     _login(data['login_lisi']['user_name'], data['login_lisi']['password'])

#每个方法执行前都会执行清理其他标签页
@pytest.fixture(autouse=True)
def close():
    yield
    First_handle = driver.current_window_handle
    n = driver.window_handles
    print(n)
    for handle in n:
        if handle != First_handle:
            driver.switch_to.window(handle)
            # 做完一系列操作后关闭school_handle
            driver.close()
            # 切换窗口会第一个窗口
    driver.switch_to.window(First_handle)
    # driver.get(data['URL'])

@pytest.fixture
def CLB(driver1):
    CLB1 = CommodityListBusiness(driver1)
    yield driver1, CLB1  # init driver对象  lg页面对象

@pytest.fixture
def delete_commodity(driver1,CLB):
    yield
    CLB[1].delete_commodity(text='道长牌T恤')

@pytest.fixture
def AB(driver1):
    AB1 = AddCommodityBusiness(driver1)
    yield driver1, AB1  # init driver对象  lg页面对象
# @pytest.fixture
# def _driver(driver1):
#     driver = DataCenterBusiness(driver1)
#     yield driver1, driver  # init driver对象  lg页面对象
#-function：每一个函数或方法都会调用
# -class：每一个类调用一次，一个类中可以有多个方法
# -module：每一个.py文件调用一次，该文件内又有多个function和class
# -session：是多个文件调用一次，可以跨.py文件调用，每个.py文件就是module
# function默认模式@pytest.fixture(scope='function')或 @pytest.fixture()



# 一、测试用例出现问题时，使用yield与request.addfinalizer（）函数哪个好？
# 答：当测试用例出现问题时，yield与request.addfinalizer（）后面的teardown都会被执行，

# 二、setup出现问题时，使用yield与request.addfinalizer（）函数哪个好？
# 答：request.addfinalizer（）函数会更好。当setup出现问题了，addfinalizer会执行teardown操作
# 总结：一个测试固件没有返回值且确保setup不会出现问题时用yield更容易理解，其他情况使用addfinalizer函数更好


#def driver1(request):
#     """定义全局driver fixture，给其它地方作参数调用"""
#     if platform.system()=='Windows':
#         print("当前运行的操作系统为windows")
#         chrome_options = Options()
#         chrome_options.add_argument('--window-size=1920,1080')  # 设置当前窗口的宽度，高度
#         # chrome_options.add_argument('--headless')  # 无界面
#         _driver = webdriver.Chrome(options=chrome_options)
#         # _driver.get(url)
#         _driver.get("https://www.oschina.net/home/login")
#         login1=LoginBusiness(_driver)
#         login1.login("18821768014","hbq19941120")
#
#     else:
#         print('当前运行的操作系统为linux')
#         chrome_options = Options()
#         chrome_options.add_argument('--no-sandbox')#解决DevToolsActivePort文件不存在报错问题
#         chrome_options.add_argument('--window-size=1920,1080')  # 设置当前窗口的宽度，高度
#         chrome_options.add_argument('--disable-gpu')#禁用GPU硬件加速，如果软件渲染器没有就位，则GPU进程将不会启动
#         chrome_options.add_argument('--disable-dev-shm-usage')#-禁用-开发-SHM-使用
#         chrome_options.add_argument('--headless')  # 无界面
#         _driver = webdriver.Chrome(options=chrome_options)
#         # _driver.get(data['URL'])
#         _driver.get("https://www.oschina.net/home/login")
#         print('打开了网页')
#
    # def end():
    #     print("全部用例执行完后 teardown quit dirver1")
    #     time.sleep(5)
    #     _driver.quit()
    #
    # # 注册一个清理函数
    # request.addfinalizer(end)
    # # 注册完清理函数后，如果在测试固件里抛出异常,清理函数照常执行
    # return _driver


